import { Injectable } from '@angular/core';
import { ApesMessageService } from '@shared/apes/message';
import { Subject } from 'rxjs';
import { filter, switchMap, tap } from 'rxjs/operators';
import { AutopartsApiService } from '@core/services/autoparts/autoparts.api.service';
import { AutopartsViewService } from '@core/services/autoparts/autoparts.view.service';

interface BaseType {
  vin?: string;
  vehicleConfig?: string, // 配置车型编码
  brandName?: string,  // 汽车厂牌名称
  epcId?: string,  // epc编码
  epcVersion?: string,  // epc版本
  dataSource?: string, // 数据来源
  keyword?: string, // 关键词
  menuName?: string // 目录名
}

@Injectable({
  providedIn: 'root',
})
export class AutopartsService {

  private baseData: BaseType = {}; // 缓存当前查询的数据

  selectMenu$ = new Subject(); // 选择主组

  selectSubgroup$ = new Subject(); // 选择子组

  selectPartsList$ = new Subject(); // 选择配件

  nextSubgroup$ = new Subject();

  getQueryParam(...param) {
    return { ...this.baseData, ...param[0] };
  }


  constructor(
    private msgService: ApesMessageService,
    private autopartsApiService: AutopartsApiService,
    private autopartsViewService: AutopartsViewService,
  ) {
    // 选中主目录
    this.selectMenu$.subscribe(data => {

      // 选中主组，清空关键词和目录名称
      this.autopartsViewService.clearKeywordAndMenuName$.next();

      // 此处 data 中包含 epcId epcVersion id(品类编码或者目录编码) dataSource（OWNER EPC）
      this.autopartsApiService.getSubgroup(this.getQueryParam(data))
        .pipe(
          tap(() => {
            this.autopartsViewService.subgroupChange$.next({});
            this.autopartsViewService.clearSecondSurface();
          }),
          filter(value => Object.keys(value).length != 0),
          tap(() => this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(false)))
        .subscribe(subgroup => {
          this.autopartsViewService.subgroupChange$.next(subgroup);
          console.log('当前主组查询出的子组', subgroup);
        });
    });

    // 选中子组
    this.selectSubgroup$.subscribe((data: any) => {
      // 如果当前为末级直接查询配件
      if (data.lastStage) {
        this.searchPartsList(data);
      } else {
        this.autopartsApiService.getSubgroup({
          ...data,
          dataSource: 'EPC',
        }).pipe(filter(value => Object.keys(value).length != 0))
          .subscribe(subgroup => {
            this.autopartsViewService.subgroupChange$.next(subgroup);
            console.log('当前子组查询出的子组', subgroup);
          });
      }
    });
  }

  /***
   * 解析 vin vehicleConfig brandName
   * @param param
   */

  parseVin(param: BaseType) {
    this.baseData = param; // 缓存初始数据
    this.autopartsViewService.init(); // 初始化界面
    this.autopartsViewService.controlSearchBtnDisable$.next(true); //disable 查询按钮

    this.autopartsApiService.parseVin(this.getQueryParam())
      .pipe(
        tap(() => this.autopartsViewService.controlSearchBtnDisable$.next(false)),
        filter(value => Object.keys(value).length != 0),
        switchMap(value => {
          let { dataSource, data: { epcId, epcVersion } } = value; // 解构赋值
          this.baseData = { ...this.baseData, epcId, epcVersion, dataSource };
          return this.autopartsApiService.getCataLog(this.getQueryParam());
        }))
      .pipe(filter(value => Object.keys(value).length != 0),
        tap(() => this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(false)))
      .subscribe(menu => {
        this.autopartsViewService.selectMenu();
        this.autopartsViewService.menuChange$.next(menu);
        this.autopartsApiService.searchVehicleConfiguration(param).pipe(
          filter(value => Object.keys(value).length != 0),
        ).subscribe(data => this.autopartsViewService.modelInfoChange$.next(data));
      });
  }

  /***
   * 解析 epcId epcVersion
   */

  parseEpcIdAndEpcVersion(param: BaseType) {
    this.autopartsViewService.init(); // 初始化界面
    this.autopartsViewService.controlSearchBtnDisable$.next(true); //disable 查询按钮
    this.baseData = { ...param, dataSource: 'INNER' }; // 缓存初始数据

    this.autopartsApiService.getCataLog(this.getQueryParam())
      .pipe(tap(() => this.autopartsViewService.controlSearchBtnDisable$.next(false)),
        filter(value => Object.keys(value).length != 0),
        tap(() => this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(false)))
      .subscribe(menu => {
        this.autopartsViewService.selectMenu();
        this.autopartsViewService.menuChange$.next(menu);
      });
  }

  /***
   * 切换目录（标准目录 原始目录）
   */
  switchMenuModel(param) {
    this.autopartsViewService.menuChange$.next([]);
    this.autopartsViewService.subgroupChange$.next({});
    this.autopartsViewService.clearSecondSurface();
    this.autopartsApiService.getCataLog(this.getQueryParam(param))
      .pipe(filter(value => Object.keys(value).length != 0))
      .subscribe(menu => {
        this.autopartsViewService.menuChange$.next(menu);
      });
  }


  /***
   * 查询关键词
   * @param param keyword
   */
  searchKeyword(param: BaseType) {
    this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(true);
    this.autopartsViewService.controlIsloading$.next(true);
    this.autopartsApiService.searchKeyword(this.getQueryParam({ keyword: param })).pipe(
      tap(() => {
        this.autopartsViewService.controlIsloading$.next(false);
        this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(false);
        this.autopartsViewService.subgroupChange$.next([]);
        this.autopartsViewService.clearSecondSurface();
      }),
      filter(value => Object.keys(value).length != 0),
    ).subscribe(subgroup => {
      this.autopartsViewService.subgroupChange$.next(subgroup);
    });
  }

  /***
   * 查询目录名称
   * @param param menuName
   */
  searchMenuName(param: BaseType) {
    if( !this.baseData.epcId || !this.baseData.epcVersion || !this.baseData.dataSource ) return;
    this.autopartsViewService.controlIsloading$.next(true);
    this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(true);
    this.autopartsApiService.searchMenuName(this.getQueryParam({ menuName: param })).pipe(
      tap(() => {
        this.autopartsViewService.controlIsloading$.next(false);
        this.autopartsViewService.controlKeywordAndMenuNameDisable$.next(false);
        this.autopartsViewService.subgroupChange$.next([]);
        this.autopartsViewService.clearSecondSurface();
      }),
      filter(value => Object.keys(value).length != 0),
    ).subscribe(subgroup => {
      this.autopartsViewService.subgroupChange$.next(subgroup);
    });
  }


  /***
   * 查询配件信息
   */

  searchPartsList(data) {
    this.autopartsApiService.getPartsList({ ...data, dataSource: 'INNER' }).pipe(tap(() => {
        this.autopartsViewService.clearSecondSurface();
      }), filter(value => Object.keys(value).length != 0),
      tap(() => {
        this.autopartsViewService.showSecondSurface(data);
      }),
    ).subscribe((partsList:any) => {
      this.autopartsViewService.controlShowBtn$.next(false);
      partsList.data.forEach(item => item.epcVersion = this.baseData.epcVersion); //写入版本用于配件图片展示
      this.autopartsViewService.partsListChange$.next(partsList);
      console.log('当前子组查询出的配件', partsList);
    });
  }

  /***
   * 修改配件的编译标记
   */
  updateParseSign(data) {
    return this.autopartsApiService.updateParseSign(this.getQueryParam(data));
  }


  /***
   * 增加代办
   */

  addToDo(data) {
    return this.autopartsApiService.sendPartsParseToDo(this.getQueryParam({...data}));
  }

}

